﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using System.IO;
using Lamex.Interface;
using DevExpress.XtraGrid.Columns;
using Lamex.Common;
using System.Xml;
using DevExpress.XtraReports.UI;

namespace Lamex.mMaterial.UI
{
    public partial class frmMC_Raw_Material_Photo : frmBaseChild
    {
        DirectoryInfo DirInfo;
        string strSql;
        DataTable dt;
        int intNum_Mat, intNum_Img;
        string path1 = "";
        string path2 = "";
        DataTable dtPrint = null;
        DataTable dtConvertSort=null;
        public frmMC_Raw_Material_Photo()
        {
            InitializeComponent();
        }

        private void frmMC_Raw_Material_Photo_Resize(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = this.Width / 2;
            splitContainerControl2.SplitterPosition = this.Width / 2;
        }

        private void frmMC_Raw_Material_Photo_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            radioGroup2.Enabled = false;
            radioGroup2.SelectedIndex = -1;

            gridControl1.UseEmbeddedNavigator = true;
            gridView1.OptionsBehavior.Editable = false;

            gridControl2.UseEmbeddedNavigator = true;
            gridControl2.MainView = gridView2;
            gridView2.OptionsBehavior.Editable = false;

            strSql = @"SELECT DISTINCT STORAGE_LOCATION
FROM WH_Raw_Material_Inventory
ORDER BY STORAGE_LOCATION";
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);

            foreach (DataRow dr in dt.Rows)
            {
                comboBoxEdit1.Properties.Items.Add(dr[0].ToString().Trim());
            }


            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\PicturePathConfig.xml");
            XmlNode xn = doc.SelectSingleNode("Pictures");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                XmlElement xe = (XmlElement)xn1;
                XmlNodeList xn2 = xe.ChildNodes;
                foreach (XmlElement x2 in xn2)
                {
                    if (x2.Name == "MtsPath")
                        path1 = x2.InnerText;
                    if (x2.Name == "MtmPath")
                        path2 = x2.InnerText;

                }
            }
        }

        private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridControl1.DataSource = null;
            gridControl2.DataSource = null;

            this.Text = "原材料图片管理";

            comboBoxEdit2.Text = "";
            comboBoxEdit2.Properties.Items.Clear();

            strSql = @"SELECT DISTINCT STORAGE_SPACE
FROM WH_Raw_Material_Inventory
WHERE STORAGE_LOCATION='" + comboBoxEdit1.Text + @"'
ORDER BY STORAGE_SPACE";
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);

            foreach (DataRow dr in dt.Rows)
            {
                comboBoxEdit2.Properties.Items.Add(dr[0].ToString().Trim());
            }

            
        }

        private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridControl1.DataSource = null;
            gridControl2.DataSource = null;

            this.Text = "原材料图片管理";
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBoxEdit2.Text))
            {
                string strWhere = "";
                if(!string.IsNullOrEmpty(comboBoxEdit1.Text))
                {
                    strWhere += " and STORAGE_LOCATION ='" + comboBoxEdit1.Text + "'";
                }
                if (!string.IsNullOrEmpty(txt_Material.Text))
                {
                    strWhere += " and a.MATERIAL_NO ='" + txt_Material.Text+ "'";
                }
                strSql = @"SELECT convert(bit,0)  as 选择, ROW_NUMBER() OVER (ORDER BY a.MATERIAL_NO ASC) AS 序号,
a.MATERIAL_NO AS 物料,convert(nvarchar(28), MATERIAL_DESC) AS 描述,
null AS 拍照顺序,
STORAGE_LOCATION AS 货架,STORAGE_SPACE AS 仓位,PHOTO_NAME AS 图片名,b.UPDATE_USER AS 维护人,b.UPDATE_TIME AS 维护时间
FROM WH_Raw_Material_Inventory AS a
LEFT JOIN WH_Raw_Material_Photo_List AS b
ON a.MATERIAL_NO=b.MATERIAL_NO
WHERE 1=1 " + strWhere+ " ORDER BY STORAGE_SPACE,a.MATERIAL_NO";


                this.Text = "物料仓：" + comboBoxEdit1.Text + " 货架明细";
            }
            else
            {
                string strWhere = "";
                if (!string.IsNullOrEmpty(comboBoxEdit2.Text))
                {
                    strWhere += " and STORAGE_SPACE ='" + comboBoxEdit2.Text + "'";
                }
                if (!string.IsNullOrEmpty(txt_Material.Text))
                {
                    strWhere += " and a.MATERIAL_NO ='" + txt_Material.Text + "'";
                }
                strSql = @"SELECT convert(bit,0) as 选择, ROW_NUMBER() OVER (ORDER BY a.MATERIAL_NO ASC) AS 序号,
a.MATERIAL_NO AS 物料,convert(nvarchar(28), MATERIAL_DESC) AS 描述,
null AS 拍照顺序,
STORAGE_LOCATION AS 货架,STORAGE_SPACE AS 仓位,PHOTO_NAME AS 图片名,b.UPDATE_USER AS 维护人,b.UPDATE_TIME AS 维护时间
FROM WH_Raw_Material_Inventory AS a
LEFT JOIN WH_Raw_Material_Photo_List AS b
ON a.MATERIAL_NO=b.MATERIAL_NO
WHERE 1=1 " + strWhere + " ORDER BY STORAGE_SPACE,a.MATERIAL_NO";


                this.Text = "物料仓：" + comboBoxEdit1.Text + " 货架，" + comboBoxEdit2.Text + " 仓位明细";
            }

            dt.Columns.Clear();
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            gridControl1.DataSource = dt;
            
            dtPrint = dt.Copy();
            //dt.Columns.Add("图片", typeof(Image));//增加图片列


            //不能放在Load事件中，因需所有列都已经在界面上加载完成之后才能生效
            setAutoCloumnWidth();
            setGridViewEditaleColumn();//设置可编辑列

            intNum_Mat = dt.Rows.Count;

            //图片预览
            if (radioGroup1.SelectedIndex == 1)
            {
                addDataSourceToPhotoList();
            }
        }

        private void addDataSourceToPhotoList()
        {
            //如已有"图片"列，则跳过
            try
            {
                dt.Columns.Add("图片", typeof(Image));//增加图片列
            }
            catch //(Exception ex)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }

            DataTable dtPic = new DataTable();
            dtPic.Columns.Add("物料");
            dtPic.Columns.Add("描述");
            dtPic.Columns.Add("图片",typeof(Image));
            //dtPic = dt.Clone();
            //此ttry...catch，因要分开监测，不同前面合并
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow drowNew = dtPic.NewRow();
                    drowNew["物料"] = dr["物料"];
                    drowNew["描述"] = dr["描述"];

                    string _path1 = path1 + dr["图片名"].ToString() + @".jpg";
                   string _path2 = path2 + dr["物料"].ToString() + @"-ISO.jpg";
                    if (!string.IsNullOrEmpty(dr["图片名"].ToString()))
                    {
                        
                        //drowNew.ItemArray = dr.ItemArray;
                        //优先加载照片，无照片，加载实体模型图
                        if (File.Exists(_path1))
                        {

                            //Image image = Image.FromFile(path1);
                            dr["图片"] = byteArrayToImage(getImageByte(_path1));
                           
                            drowNew["图片"] = byteArrayToImage(getImageByte(_path1));
                        }
                        else if (File.Exists(_path2))
                        {
                            dr["图片"] = byteArrayToImage(getImageByte(_path2));
                            
                            drowNew["图片"] = byteArrayToImage(getImageByte(_path1));
                            //dr["图片"] = SaveImage(path2);
                        }
                        dtPic.Rows.Add(drowNew);
                    }
                }
                //gridView2.
                gridControl2.DataSource = dtPic;

                //DevExpress GridControl 关于使用CardView的一点小结
                //https://blog.csdn.net/yang472024191/article/details/40536327?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
                //图片大小控制
                cardView1.OptionsBehavior.FieldAutoHeight = true;
                //layoutView1.OptionsBehavior.FieldAutoHeight = true;
                //打开Run Designer，view选项中的外观中设置cardWidth（也就显示的cardView/layoutView1的宽度），
                //再进入In-Place Editor Repository,选中respositoryItemPictureEdit1在行为中设置CustomHeight（也就是cardView的高），把SizeMode改为Zoom即可
            }
            catch //(Exception ex)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }

        public byte[] SaveImage(String path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
            BinaryReader br = new BinaryReader(fs);
            byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
            return imgBytesIn;
        }

        private void txtCurPath_DoubleClick(object sender, EventArgs e)
        {
            GetProcessPath();
        }

        private void btnGetPath_Click(object sender, EventArgs e)
        {
            GetProcessPath();
        }

        private void sbtnImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (radioGroup1.SelectedIndex == 0)//图片导入
                {
                    if (intNum_Img != intNum_Mat)
                    {
                        //XtraMessageBox.Show("图片文件与物料清单数量不匹配，请检查！", "提示");
                        //return;

                        if (DevExpress.XtraEditors.XtraMessageBox.Show("图片文件与物料清单数量不匹配，是否继续导入？" + "\r\n\r\n" + "继续导入将忽略不匹配项！", "提示",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            goto next;

                    }

                    next:
                    //XtraMessageBox.Show("TO DO...！", "提示", MessageBoxButtons.OK);

                    //图片关联导入，TO DO...
                    //检查用户指定路径下的图片文件的长宽是否符合要求
                    //按用户要求大小将文件裁切后复制到S:\TX-Public\TX-MFG\PPC\Material_Image
                    //用户原始路径下的图片文件不进行任何处理，方便用户发现有错误后，再次关联
                    //左边表按[拍照顺序]升序排列后，
                    //将右边图片名按对应关系写入[WH_Raw_Material_Photo_List]，并回刷到右边表中
                    //int iLeftCount = intNum_Img;
                    //if(gridView1.RowCount>gridView2.RowCount)
                    //{
                    //    DevExpress.XtraEditors.XtraMessageBox.Show("图片数目需大于左边数据");
                    //}
                    int iCheck = 0;
                    int iNum = gridView1.RowCount;
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                      if(string.IsNullOrEmpty(gridView1.GetRowCellValue(i, "拍照顺序").ToString()))
                      {
                            iCheck++;
                      }
                    }
                    //if(iCheck!= iNum &&iCheck!=0)
                    //{
                    //    XtraMessageBox.Show("拍照顺序没有输全!");
                    //    return;
                    //}

                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        if (!string.IsNullOrEmpty(gridView1.GetRowCellValue(i, "拍照顺序").ToString()))
                        {
                            if (i == intNum_Img)
                            {
                                break;
                            }
                            else
                            {
                                int row = gridView2.RowCount;
                                if (gridView2.GetRowCellValue(int.Parse(gridView1.GetRowCellValue(i, "拍照顺序").ToString()) - 1, "图片名称") == null)
                                    continue;
                                string _filename = gridView2.GetRowCellValue(int.Parse(gridView1.GetRowCellValue(i, "拍照顺序").ToString())-1, "图片名称").ToString();
                                string filename = _filename.Substring(0, _filename.LastIndexOf('.'));
                                gridView1.SetRowCellValue(i, "图片名", filename);
                                string mATERIAL_NO = gridView1.GetRowCellValue(i, "物料").ToString();
                                //string picName = gridView2.GetRowCellValue(i, "图片名称").ToString();
                                string targetPaht = path1 + _filename;
                                string localpath = txtCurPath.Text + @"\" + _filename;
                                if (File.Exists(targetPaht))
                                    File.Delete(targetPaht);
                                File.Copy(localpath, targetPaht);


                                string sqlCheck = " select * from WH_Raw_Material_Photo_List where MATERIAL_NO='" + mATERIAL_NO + "' ";
                                string sql = " update WH_Raw_Material_Photo_List set PHOTO_NAME='" + filename + "' where MATERIAL_NO='" + mATERIAL_NO + "' ";
                                //check WH_Raw_Material_Photo_List if it has record. if it has update else insert
                                DataTable dtRow = Lamex.Base.BaseBuildSql.GetDataTableBySql(sqlCheck);
                                if (dtRow.Rows.Count != 0)
                                {
                                    Lamex.Base.BaseBuildSql.ExecuteNonQuery(sql);
                                }
                                else
                                {
                                    Lamex.Base.BaseBuildSql.ExecuteNonQuery(@"insert into WH_Raw_Material_Photo_List(MATERIAL_NO,PHOTO_NAME,UPDATE_USER,UPDATE_TIME)
                                                                    values('" + mATERIAL_NO + "','" + filename + "','" + Loginer.CurrentUser.AccountName + "',getdate())");
                                }


                            }
                        }
                    }

                    DataTable dtConvert =((DataView) gridView1.DataSource).ToTable().Select("", "拍照顺序 asc").CopyToDataTable();
                    if (dtConvertSort!=null)
                        dtConvertSort.Columns.Clear();
                    DataRow[] hasNumSort = dtConvert.Select("拍照顺序 is not null", "拍照顺序 asc");
                    DataRow[] NoHasNum = dtConvert.Select("拍照顺序 is null", "拍照顺序 asc");
                    dtConvertSort = dtConvert.Clone();
                    foreach(DataRow dr in hasNumSort)
                    {
                        DataRow drow = dtConvertSort.NewRow();
                        drow.ItemArray = dr.ItemArray;
                        dtConvertSort.Rows.Add(drow);
                    }

                    foreach (DataRow dr in NoHasNum)
                    {
                        DataRow drow = dtConvertSort.NewRow();
                        drow.ItemArray = dr.ItemArray;
                        dtConvertSort.Rows.Add(drow);
                    }

                    //dtConvertSort = dtConvert.Select("", "拍照顺序 asc").CopyToDataTable() ;

                    int RowNum= 1;
                    foreach (DataRow dr in dtConvertSort.Rows)
                    {

                        dr["序号"] = RowNum;
                        RowNum++;
                    }
                    gridControl1.DataSource = dtConvertSort;
                    dt.Clear();
                    dt = dtConvertSort.Copy();
                    //dtConvertSort.Columns.Add("图片", typeof(Image));//增加图片列
                    //dt.Columns.Clear();
                    //dt = dtConvertSort;
                    //
                    #region""
                    //if(iCheck==0)
                    //{
                    //    for (int i = 0; i < gridView1.RowCount; i++)
                    //    {
                    //        if (i == intNum_Img)
                    //        {
                    //            break;
                    //        }
                    //        else
                    //        {
                    //            int row = gridView2.RowCount;
                    //            string _filename = gridView2.GetRowCellValue(i, "图片名称").ToString();
                    //            string filename = _filename.Substring(0, _filename.LastIndexOf('.'));
                    //            gridView1.SetRowCellValue(i, "图片名", filename);
                    //            string mATERIAL_NO = gridView1.GetRowCellValue(i, "物料").ToString();
                    //            //string picName = gridView2.GetRowCellValue(i, "图片名称").ToString();
                    //            string targetPaht = path1 + _filename;
                    //            string localpath = txtCurPath.Text + @"\" + _filename;
                    //            if (File.Exists(targetPaht))
                    //                File.Delete(targetPaht);
                    //            File.Copy(localpath, targetPaht);


                    //            string sqlCheck = " select * from WH_Raw_Material_Photo_List where MATERIAL_NO='" + mATERIAL_NO + "' ";
                    //            string sql = " update WH_Raw_Material_Photo_List set PHOTO_NAME='" + filename + "' where MATERIAL_NO='" + mATERIAL_NO + "' ";
                    //            //check WH_Raw_Material_Photo_List if it has record. if it has update else insert
                    //            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(sqlCheck);
                    //            if (dt.Rows.Count != 0)
                    //            {

                    //                Lamex.Base.BaseBuildSql.ExecuteNonQuery(sql);
                    //            }
                    //            else
                    //            {
                    //                Lamex.Base.BaseBuildSql.ExecuteNonQuery(@"insert into WH_Raw_Material_Photo_List(MATERIAL_NO,PHOTO_NAME,UPDATE_USER,UPDATE_TIME)
                    //                                                values('" + mATERIAL_NO + "','" + filename + "','" + Loginer.CurrentUser.AccountName + "',getdate())");
                    //            }


                    //        }
                    //    }
                    //}
                    //else
                    //{
                    //    for (int i = 0; i < gridView1.RowCount; i++)
                    //    {
                    //        if (i == intNum_Img)
                    //        {
                    //            break;
                    //        }
                    //        else
                    //        {
                    //            int row = gridView2.RowCount;
                    //            int iSort = int.Parse(gridView1.GetRowCellValue(i, "拍照顺序").ToString()); //获取拍照顺序
                    //            iSort -= 1;
                    //            string _filename = gridView2.GetRowCellValue(iSort, "图片名称").ToString();
                    //            string filename = _filename.Substring(0, _filename.LastIndexOf('.'));

                    //            gridView1.SetRowCellValue(i, "图片名", filename);
                    //            string mATERIAL_NO = gridView1.GetRowCellValue(i, "物料").ToString();
                    //            //string picName = gridView2.GetRowCellValue(iSort, "图片名称").ToString();
                    //            string targetPaht = path1 + _filename;
                    //            string localpath = txtCurPath.Text + @"\" + _filename;
                    //            if (File.Exists(targetPaht))
                    //                File.Delete(targetPaht);
                    //            File.Copy(localpath, targetPaht);


                    //            string sqlCheck = " select * from WH_Raw_Material_Photo_List where MATERIAL_NO='" + mATERIAL_NO + "' ";
                    //            string sql = " update WH_Raw_Material_Photo_List set PHOTO_NAME='" + filename + "' where MATERIAL_NO='" + mATERIAL_NO + "' ";
                    //            //check WH_Raw_Material_Photo_List if it has record. if it has update else insert
                    //            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(sqlCheck);
                    //            if (dt.Rows.Count != 0)
                    //            {

                    //                Lamex.Base.BaseBuildSql.ExecuteNonQuery(sql);
                    //            }
                    //            else
                    //            {
                    //                Lamex.Base.BaseBuildSql.ExecuteNonQuery(@"insert into WH_Raw_Material_Photo_List(MATERIAL_NO,PHOTO_NAME,UPDATE_USER,UPDATE_TIME)
                    //                                                values('" + mATERIAL_NO + "','" + filename + "','" + Loginer.CurrentUser.AccountName + "',getdate())");
                    //            }


                    //        }
                    //    }
                    //}

                    #endregion
                }
                else
                {
                    XtraMessageBox.Show("请选择导入操作！", "提示");
                }
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void sbtnPrint_Click(object sender, EventArgs e)
        {
            //标签打印，TO DO...
            if (radioGroup1.SelectedIndex == 1)
            {
                //  Lamex.Common.ExecelHelper.GridViewToPrint(gridControl2, this.Text);
                //数据处理
                
                DataTable dtData = dtPrint.Clone();
                dtData.Columns.Add("图片",typeof(Image));
                int icheck = 0;
                for (int m=0;m< gridView1.RowCount; m++)
                {
                    if (gridView1.GetRowCellValue(m,"选择").ToString().ToLower() == "true")
                        icheck++;
                }
                if(icheck==0)
                {
                    
                    for (int m = 0; m < gridView1.RowCount; m++)
                    {
                        string _path1 = path1 + gridView1.GetRowCellValue(m, "图片名").ToString() + @".jpg";
                        string _path2 = path2 + gridView1.GetRowCellValue(m, "物料").ToString() + @"-ISO.jpg";
                        DataRow dr = dtData.NewRow();
                        dr["物料"] = gridView1.GetRowCellValue(m, "物料");
                        dr["描述"] = gridView1.GetRowCellValue(m, "描述");
                        if (File.Exists(_path1))
                        {
                            Image img = Lamex.Common.DataConverter.resizeImageFromFile(_path1, 190, 247, false, true);

                            dr["图片"] = img;
                        }
                        else if (File.Exists(_path2))
                        {
                            Image img = Lamex.Common.DataConverter.resizeImageFromFile(_path2, 190, 247, false, true);
                            dr["图片"] = img;
                        }

                        dtData.Rows.Add(dr);
                    }
                }
                else
                {
                    for (int m = 0; m < gridView1.RowCount; m++)
                    {
                        if (gridView1.GetRowCellValue(m, "选择").ToString().ToLower() == "true")
                        {
                            string _path1 = path1 + gridView1.GetRowCellValue(m, "图片名").ToString() + @".jpg";
                            string _path2 = path2 + gridView1.GetRowCellValue(m, "物料").ToString() + @"-ISO.jpg";
                            DataRow dr = dtData.NewRow();
                            dr["物料"] = gridView1.GetRowCellValue(m, "物料");
                            dr["描述"] = gridView1.GetRowCellValue(m, "描述");
                            if (File.Exists(_path1))
                            {
                                Image img = Lamex.Common.DataConverter.resizeImageFromFile(_path1, 190, 247, false, true);

                                dr["图片"] = img;
                            }
                            else if (File.Exists(_path2))
                            {
                                Image img = Lamex.Common.DataConverter.resizeImageFromFile(_path2, 190, 247, false, true);
                                dr["图片"] = img;
                            }
                            dtData.Rows.Add(dr);
                        }
                    }
                }
                //foreach (DataRow dr in dtData.Rows)
                //{

                //    string _path1 = path1 + dr["图片名"].ToString() + @".jpg";
                //    string _path2 = path2 + dr["物料"].ToString() + @"-ISO.jpg";

                //    //优先加载照片，无照片，加载实体模型图
                //    if (File.Exists(_path1))
                //    {
                //        //Image image = Image.FromFile(path1);
                //        Image img =Lamex.Common.DataConverter.resizeImageFromFile(_path1,190, 190, false,true);
       
                //        dr["图片"] = img;
                //        //dr["图片"] = SaveImage(path1);
                //    }
                //    else if (File.Exists(_path2))
                //    {
                //        Image img = Lamex.Common.DataConverter.resizeImageFromFile(_path2, 190, 190, false, true);
                //        dr["图片"] = img;
                //        //dr["图片"] = SaveImage(path2);
                //    }
                //}
                string s = "";
                DataTable _dtPrint = dtData.Select("图片 is not null").CopyToDataTable();
                FrmMC_XtraReport frm = new FrmMC_XtraReport(_dtPrint);
                frm.ShowPreviewDialog();
            }
            else
            {
                XtraMessageBox.Show("请选择图片预览！", "提示");
            }
        }

        private void GetProcessPath()
        {
            //XtraFolderBrowserDialog folder = new XtraFolderBrowserDialog();
            FolderBrowserDialog folder = new FolderBrowserDialog();

            //设置默认根目录是桌面
            folder.RootFolder = Environment.SpecialFolder.Desktop;
            //folder.SelectedPath = @"S:\TX-Public\TX-MFG\PPC\Material_Image";//用绝对路径时不能正确指向
            folder.SelectedPath = @"D:\Temp";

            //设置对话框说明
            folder.Description = "请选择文件搜索路径:";
            try
            {
                if (folder.ShowDialog() == DialogResult.OK)
                {
                    txtCurPath.Text = folder.SelectedPath;
                }

                AddDataToGridview();
            }
            catch //(Exception ex)
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, MessageBoxButtons.OK);
            }
        }

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtCurPath.Text = "";
            gridControl2.DataSource = null;
            gridView2.Columns.Clear(); 
            cardView1.Columns.Clear();
            layoutView1.Columns.Clear();

            if (radioGroup1.SelectedIndex == 0)//图片导入
            {
                sbtnImport.Enabled = true;
                sbtnPrint.Enabled = false;
                splitContainerControl1.Panel2.Enabled = true;

                radioGroup2.Enabled = false;
                radioGroup2.SelectedIndex = -1;

                gridControl2.MainView = gridView2;
            }
            else if (radioGroup1.SelectedIndex == 1 || radioGroup1.SelectedIndex == 2)//图片预览
            {
                sbtnImport.Enabled = false; 
                sbtnPrint.Enabled = true;
                splitContainerControl1.Panel2.Enabled = false;

                radioGroup2.Enabled = true;
                radioGroup2.SelectedIndex = 0;

                gridControl2.MainView = cardView1;
               
                addDataSourceToPhotoList();
            }
        }

        private void radioGroup2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioGroup2.SelectedIndex == 0)//卡片视图
            {
                gridControl2.MainView = cardView1;
            }
            else if (radioGroup2.SelectedIndex == 1)//布局视图
            {
                gridControl2.MainView = layoutView1;
            }
        }

        private void AddDataToGridview()
        {
            DirInfo = new DirectoryInfo(txtCurPath.Text);
            
           DataTable  dtsort = new DataTable();
            dtsort.Columns.Add("图片名称", typeof(string));
            dtsort.Columns.Add("文件大小", typeof(int));
            dtsort.Columns.Add("创建时间", typeof(DateTime));

            foreach (FileInfo fileinfo in DirInfo.GetFiles())
            {
                if (fileinfo.Name.EndsWith(".jpg") || fileinfo.Name.EndsWith(".png") || fileinfo.Name.EndsWith(".JPG"))
                {
                    DataRow row = dtsort.NewRow();
                    //row["Name"] = fileinfo.FullName;
                    row["图片名称"] = fileinfo.Name;
                    row["文件大小"] = fileinfo.Length;
                    row["创建时间"] = fileinfo.CreationTime;
                    dtsort.Rows.Add(row);
                }
            }
            gridControl2.DataSource = dtsort;
            intNum_Img = dtsort.Rows.Count;
        }

        public override void DoView(IButtonInfo sender)
        {
            btnRefresh_Click(null, null);
            base.DoView(sender);
        }

        public override void DoImport(IButtonInfo sender)
        {
            sbtnImport_Click(null, null);
            base.DoImport(sender);
        }

        public override void DoPrint(IButtonInfo sender)
        {
            sbtnPrint_Click(null, null);
            //改为打印表
           // ExecelHelper.GridViewToPrint(gridControl1, this.Text);
            base.DoPrint(sender);
        }

        //设置可编辑数据列，设置特定列可编辑，必须在加载数据后执行
        private void setGridViewEditaleColumn()
        {
            gridView1.OptionsBehavior.Editable = true;
            gridView1.OptionsBehavior.ReadOnly = false;

            foreach (GridColumn c in gridView1.Columns)
            {
                if (c.Name == "col拍照顺序")
                {
                    c.OptionsColumn.ReadOnly = false;
                    c.OptionsColumn.AllowEdit = true;
                }
                else
                {
                    c.OptionsColumn.ReadOnly = true;
                    c.OptionsColumn.AllowEdit = false;
                }
            }

            gridView1.Columns["选择"].OptionsColumn.ReadOnly = false;
            gridView1.Columns["选择"].OptionsColumn.AllowEdit = true;
        }

        private void layoutView1_Click(object sender, EventArgs e)
        {
           // int irow = layoutView1.FocusedRowHandle;
           //string PartNo = gridView2.GetFocusedRowCellValue("图片").ToString();
        }

        /// <summary>
        /// 自适应列宽，显示横向滚轴，只有当所有列都已经在界面上加载完成之后才能生效
        /// </summary>
        public void setAutoCloumnWidth()
        {
            //自适应列宽
            gridView1.BestFitColumns();
            gridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            gridView1.OptionsView.ColumnAutoWidth = false;
        }

        /// <summary>
        /// 根据图片路径返回图片的字节流byte[]
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <returns>返回的字节流</returns>
        private byte[] getImageByte(string imagePath)
        {
            FileStream files = new FileStream(imagePath, FileMode.Open);
            byte[] imgByte = new byte[files.Length];
            files.Read(imgByte, 0, imgByte.Length);
            files.Close();
            return imgByte;
        }

        private void gridControl1_MouseClick(object sender, MouseEventArgs e)
        {
            int handle = gridView1.FocusedRowHandle;
            if (radioGroup1.SelectedIndex == 1)
            {
                if(cardView1.RowCount!=0)
                {
                    cardView1.FocusedRowHandle = handle;
                }
            }
        }

        private void menuExport_Click(object sender, EventArgs e)
        {
            ExecelHelper.GridViewToPrint(gridControl1, this.Text);
        }

        /// <summary>
        /// 字节数组生成图片
        /// </summary>
        /// <param name="Bytes">字节数组</param>
        /// <returns>图片</returns>
        private Image byteArrayToImage(byte[] Bytes)
        {
            MemoryStream ms = new MemoryStream(Bytes);
            return Bitmap.FromStream(ms, true);
        }
    }
}